const express = require("express");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const Router = require("./user");
const app = express();
const server = require('http').Server(app);
const io = require("socket.io")(server);

const model = require('./model');
const Chat = model.getModel('chat');


app.use(cookieParser());
app.use(bodyParser.json());

app.use("/user", Router);

io.on("connection", (socket) => {
  console.log("有客户端连接了socket");
  socket.on("sendMsg", (data) => {
    const {from, to, content} = data;
    const chatId = [from, to].sort().join('_');
    const create_time = Date.now();
    Chat.create({from, to, content, chatId, create_time}, (err, doc) => {
      if (err) {
        return io.emit('err', err.toString());
      }
      console.log("发送消息", doc);
      return io.emit('recMsg', doc)
    })
  });


});

server.listen(9999, function () {
  console.log("server running at port 9999")
});
